﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using ClumsyWordsWP8.Resources;
using System.Windows.Media;
using ClumsyWordsPortableLibrary.Model;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Security.Cryptography;
using System.Text;

namespace ClumsyWordsWP8
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();

            if (!IsolatedStorageSettings.ApplicationSettings.Contains("InitialLaunch"))
            { 
                this.WriteTokenToSettings("http://www.stands4.com/services/v2/defs.php?", "uid=3021", "tokenid=vE8RzRNRjAHQIJuR&word=");
                IsolatedStorageSettings.ApplicationSettings["InitialLaunch"] = "passed";
            }

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;

            // Sample code to localize the ApplicationBar
            BuildLocalizedApplicationBar();

            // Set the items for the part of speech filter control
            //this.PartOfSpeechFilterPicker.ItemsSource = Enum.GetValues(typeof(PartOfSpeech)).Cast<PartOfSpeech>();
        }

        // Load data for the ViewModel RecentItems and FavouriteItems
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }
        }

        // Sample code for building a localized ApplicationBar
        private void BuildLocalizedApplicationBar()
        {
            // Set the page's ApplicationBar to a new instance of ApplicationBar.
            ApplicationBar = new ApplicationBar();

            ApplicationBarIconButton appBarButtonSearch = new ApplicationBarIconButton(new Uri("/Assets/AppBar/feature.search.png", UriKind.Relative));
            appBarButtonSearch.Text = AppResources.AppBarButtonSearchText;
            ApplicationBar.Buttons.Add(appBarButtonSearch);

            appBarButtonSearch.Click += appBarButtonSearch_Click;

            ApplicationBarIconButton appBarButtonAddToFavs = new ApplicationBarIconButton(new Uri("Assets/AppBar/favs.addto.png", UriKind.Relative));
            appBarButtonAddToFavs.Text = AppResources.AppBarButtonAddToFavsText;
            ApplicationBar.Buttons.Add(appBarButtonAddToFavs);

            appBarButtonAddToFavs.Click += appBarButtonAddToFavs_Click;

            ApplicationBarIconButton appBarButtonClear = new ApplicationBarIconButton(new Uri("/Toolkit.Content/ApplicationBar.Cancel.png", UriKind.Relative));
            appBarButtonClear.Text = AppResources.AppBarButtonClearText;
            ApplicationBar.Buttons.Add(appBarButtonClear);

            appBarButtonClear.Click += appBarButtonClear_Click;

            // Create a new menu item with the localized string from AppResources.
            ApplicationBarMenuItem appBarMenuItemClearRecent = new ApplicationBarMenuItem(AppResources.AppBarMenuItemClearRecentText);
            ApplicationBar.MenuItems.Add(appBarMenuItemClearRecent);

            appBarMenuItemClearRecent.Click += appBarMenuItemClearRecent_Click;

            ApplicationBarMenuItem appBarMenuItemSettings = new ApplicationBarMenuItem(AppResources.AppBarMenuItemSettingsText);
            ApplicationBar.MenuItems.Add(appBarMenuItemSettings);

            appBarMenuItemSettings.Click += appBarMenuItemSettings_Click;
        }

        void appBarMenuItemSettings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("SettingsPage.xaml", UriKind.Relative));
        }

        void appBarMenuItemClearRecent_Click(object sender, EventArgs e)
        {
            App.ViewModel.RecentItems.Clear();
        }

        void appBarButtonClear_Click(object sender, EventArgs e)
        {
            if (App.ViewModel.SearchResult != null)
            {
                App.ViewModel.SearchResult = new TermDefinition();
            }
        }

        async void appBarButtonSearch_Click(object sender, EventArgs e)
        {
            if (this.SearchPanel.Visibility == Visibility.Collapsed) this.SearchPanel.Visibility = Visibility.Visible;
            else
            {
                string key = this.ReadTokenFromSettings();
                App.ViewModel.SearchResult = await App.ViewModel.CheckWordAsync(this.SearchBox.Text, key);
                App.ViewModel.SearchTerm = this.SearchBox.Text;
                //TODO : add to recent if enabled

                
                

                //Hide the search box
                this.SearchPanel.Visibility = Visibility.Collapsed;
            }
            //TODO : check if the App.ViewModel.SearchResult is empty and provide a no-data message
        }

        private void UpdateRecentItems()
        {
            if (App.ViewModel.RecentItems.Count > 20)
            {
                App.ViewModel.RecentItems.RemoveAt(19);
                App.ViewModel.RecentItems.Add(App.ViewModel.SearchResult);
            }
        }

        private void appBarButtonAddToFavs_Click(object sender, EventArgs e)
        {
            App.ViewModel.FavouriteItems.Add(App.ViewModel.SearchResult);
        }

        private void WriteTokenToSettings(string url, string userId, string token)
        {
            byte[] UrlByte = Encoding.UTF8.GetBytes(url);
            byte[] UserIdByte = Encoding.UTF8.GetBytes(userId);
            byte[] TokenByte = Encoding.UTF8.GetBytes(token);

            byte[] ProtectedUrlByte = ProtectedData.Protect(UrlByte, null);
            byte[] ProtectedUserIdByte = ProtectedData.Protect(UserIdByte, null);
            byte[] ProtectedTokenByte = ProtectedData.Protect(TokenByte, null);

            IsolatedStorageSettings.ApplicationSettings["ServiceUrl"] = ProtectedUrlByte;
            IsolatedStorageSettings.ApplicationSettings["ServiceUserId"] = ProtectedUserIdByte;
            IsolatedStorageSettings.ApplicationSettings["ServiceToken"] = ProtectedTokenByte;
        }

        private string ReadTokenFromSettings()
        {
            byte[] ProtectedUrlByte = null;
            byte[] ProtectedUserIdByte = null;
            byte[] ProtectedTokenByte = null;
            if (IsolatedStorageSettings.ApplicationSettings.Contains("ServiceUrl")
                && IsolatedStorageSettings.ApplicationSettings.Contains("ServiceUserId")
                && IsolatedStorageSettings.ApplicationSettings.Contains("ServiceToken"))
            {
                ProtectedUrlByte = IsolatedStorageSettings.ApplicationSettings["ServiceUrl"] as byte[];
                ProtectedUserIdByte = IsolatedStorageSettings.ApplicationSettings["ServiceUserId"] as byte[];
                ProtectedTokenByte = IsolatedStorageSettings.ApplicationSettings["ServiceToken"] as byte[];
            }
            else
            {
                return string.Empty;
            }

            byte[] UrlByte = ProtectedData.Unprotect(ProtectedUrlByte, null);
            byte[] UserIdByte = ProtectedData.Unprotect(ProtectedUserIdByte, null);
            byte[] TokenByte = ProtectedData.Unprotect(ProtectedTokenByte, null);

            string url = Encoding.UTF8.GetString(UrlByte, 0, UrlByte.Length);
            string userId = Encoding.UTF8.GetString(UserIdByte, 0, UserIdByte.Length);
            string token = Encoding.UTF8.GetString(TokenByte, 0, TokenByte.Length);
            return String.Format("{0}{1}&{2}", url, userId, token);
        }

        //private void ToggleSwitch_Checked(object sender, RoutedEventArgs e)
        //{
        //    App.ViewModel.IsAddToRecentEnabled = true;
        //    this.AddToRecentSwitch.Content = "On";
        //    this.Pivot.IsLocked = false;
        //}

        //private void ToggleSwitch_Unchecked(object sender, RoutedEventArgs e)
        //{
        //    App.ViewModel.IsAddToRecentEnabled = false;
        //    this.AddToRecentSwitch.Content = "Off";
        //    this.Pivot.IsLocked = false;
        //}

        //private void FilterSearchResultByPartOfSpeech(WordDefinitionViewModel wordDefinitions)
        //{
        //    //Get the selected part of speech
        //    PartOfSpeech filterBy = (PartOfSpeech)this.PartOfSpeechFilterPicker.SelectedItem;

        //    //Create a new collection of word definitions which match the condition
        //    WordDefinitionViewModel filteredItems = new WordDefinitionViewModel();
        //    //filteredItems.Term = App.ViewModel.SearchResult.Term;

        //    if (wordDefinitions.TermPropertiesList != null)
        //    {
        //        foreach (var wordDefinition in wordDefinitions.TermPropertiesList)
        //        {
        //            if (wordDefinition.PartOfSpeech != null)
        //            {
        //                if (wordDefinition.PartOfSpeech == filterBy || filterBy == PartOfSpeech.all) filteredItems.TermPropertiesList.Add(wordDefinition);
        //            }
        //        }

        //        //Set the ItemsSource of the SearchResultsList to the new collection
        //        this.SearchResultsList.ItemsSource = filteredItems.TermPropertiesList;
        //    }
        //}
    }
}